//
//  GPNaviVC.m
//  PFAMapDemo
//
//  Created by 原鹏飞 on 2018/11/5.
//  Copyright © 2018 原鹏飞. All rights reserved.
//

#import "GPNaviVC.h"

#import "SpeechSynthesizer.h" // 导航语音功能
#import "MoreMenuView.h"

#define kScreenWidth

@interface GPNaviVC () <AMapNaviDriveManagerDelegate, AMapNaviDriveViewDelegate, MoreMenuViewDelegate>

@property (nonatomic, strong) AMapNaviPoint *startPoint;
@property (nonatomic, strong) AMapNaviPoint *endPoint;
@property (nonatomic, strong) MoreMenuView *moreMenu;

@end

@implementation GPNaviVC

#pragma mark - 控制器生命周期（life cycle）

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    [self setNavigationBackItem];
    
    [self initProperties];
    
    [self initDriveView];
    
    [self initDriveManager];
    
    [self initMoreMenu];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.toolbarHidden = YES;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self calculateRoute];
}


- (void)viewWillLayoutSubviews {
    // iOS8之前的横竖屏切换
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
        UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
        interfaceOrientation = self.interfaceOrientation;
        
        if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) {
            self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        } else if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
            self.driveView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        }
    }
}


// 驾车导航界面横竖屏切换后的回调函数
- (void)driveView:(AMapNaviDriveView *)driveView didChangeOrientation:(BOOL)isLandscape {
//    if (isLandscape) {
//        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//    } else {
//        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
//    }
}


- (BOOL)prefersStatusBarHidden {
    return YES;
}


#pragma mark - Initalization

- (void)initProperties {
    //设置导航的起点和终点
    self.startPoint = [AMapNaviPoint locationWithLatitude:_currentUL.coordinate.latitude longitude:_currentUL.coordinate.longitude];
    self.endPoint = [AMapNaviPoint locationWithLatitude:self.targetLocation.coordinate.latitude longitude:self.targetLocation.coordinate.longitude];
}


- (void)initDriveManager {
    if (self.driveManager == nil) {
        self.driveManager = [AMapNaviDriveManager sharedInstance];
        self.driveManager.delegate = self;
        
        [self.driveManager setMultipleRouteNaviMode:YES];   // 多路径规划，最好在创建单例时设置
        [self.driveManager setAllowsBackgroundLocationUpdates:YES];
        [self.driveManager setPausesLocationUpdatesAutomatically:NO];
        
        //将driveView添加为导航数据的Representative，使其可以接收到导航诱导数据
        [self.driveManager addDataRepresentative:self.driveView];
        
    }
}


- (void)initDriveView {
    if (_driveView == nil) {
        //        self.driveView = [[AMapNaviDriveView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _driveView = [[AMapNaviDriveView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.driveView setDelegate:self];
        [self.view addSubview:self.driveView];
    }
}


- (void)initMoreMenu {
    if (self.moreMenu == nil) {
        self.moreMenu = [[MoreMenuView alloc] init];
        self.moreMenu.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.moreMenu.delegate = self;
    }
}


#pragma mark - 路径规划（calculate route）

- (void)calculateRoute {
    // 规划驾车路径
    [self.driveManager calculateDriveRouteWithStartPoints:@[self.startPoint]
                                                endPoints:@[self.endPoint]
                                                wayPoints:nil
                                          drivingStrategy:AMapNaviDrivingStrategySingleDefault];
}


#pragma mark - AMapNaviDriveManager Delegate

- (void)driveManager:(AMapNaviDriveManager *)driveManager error:(NSError *)error {
    NSLog(@"error:{%ld - %@}", (long)error.code, error.localizedDescription);
}


- (void)driveManagerOnCalculateRouteSuccess:(AMapNaviDriveManager *)driveManager {
    NSLog(@"onCalculateRouteSuccess");
    
    //算路成功后开始GPS导航
    [self.driveManager startGPSNavi];
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteFailure:(NSError *)error {
    NSLog(@"onCalculateRouteFailure:{%ld - %@}", (long)error.code, error.localizedDescription);
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager didStartNavi:(AMapNaviMode)naviMode {
    NSLog(@"didStartNavi");
}


- (void)driveManagerNeedRecalculateRouteForYaw:(AMapNaviDriveManager *)driveManager {
    NSLog(@"needRecalculateRouteForYaw");
}


- (void)driveManagerNeedRecalculateRouteForTrafficJam:(AMapNaviDriveManager *)driveManager {
    NSLog(@"needRecalculateRouteForTrafficJam");
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager onArrivedWayPoint:(int)wayPointIndex {
    NSLog(@"onArrivedWayPoint:%d", wayPointIndex);
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType {
    NSLog(@"playNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
    
    [[SpeechSynthesizer sharedSpeechSynthesizer] speakString:soundString];
}


- (void)driveManagerDidEndEmulatorNavi:(AMapNaviDriveManager *)driveManager {
    NSLog(@"didEndEmulatorNavi");
}


- (void)driveManagerOnArrivedDestination:(AMapNaviDriveManager *)driveManager {
    NSLog(@"onArrivedDestination");
}


#pragma mark - AMapNaviDriveViewDelegate

/**
 * @brief 导航界面关闭按钮点击时的回调函数
 * @param driveView 驾车导航界面
 */
- (void)driveViewCloseButtonClicked:(AMapNaviDriveView *)driveView {
    //停止导航
    [self.driveManager stopNavi];
    [self.driveManager removeDataRepresentative:self.driveView];
    
    //停止语音
    [[SpeechSynthesizer sharedSpeechSynthesizer] stopSpeak];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)driveViewMoreButtonClicked:(AMapNaviDriveView *)driveView
{
    //配置MoreMenu状态
    [self.moreMenu setTrackingMode:self.driveView.trackingMode];
    [self.moreMenu setShowNightType:self.driveView.showStandardNightType];
    
    [self.moreMenu setFrame:self.view.bounds];
    [self.view addSubview:self.moreMenu];
}

- (void)driveViewTrunIndicatorViewTapped:(AMapNaviDriveView *)driveView {
    NSLog(@"TrunIndicatorViewTapped");
}

- (void)driveView:(AMapNaviDriveView *)driveView didChangeShowMode:(AMapNaviDriveViewShowMode)showMode {
    NSLog(@"didChangeShowMode:%ld", (long)showMode);
}

#pragma mark - MoreMenu Delegate

- (void)moreMenuViewFinishButtonClicked {
    [self.moreMenu removeFromSuperview];
}

- (void)moreMenuViewNightTypeChangeTo:(BOOL)isShowNightType {
    [self.driveView setShowStandardNightType:isShowNightType];
}

- (void)moreMenuViewTrackingModeChangeTo:(AMapNaviViewTrackingMode)trackingMode {
    [self.driveView setTrackingMode:trackingMode];
}

@end
